package com.freeter.config;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.tio.server.ServerGroupContext;
import org.tio.server.TioServer;
import org.tio.server.intf.ServerAioHandler;
import org.tio.server.intf.ServerAioListener;
import org.voovan.network.aio.AioServerSocket;
import org.voovan.network.filter.StringFilter;
import org.voovan.network.messagesplitter.LineMessageSplitter;

import com.freeter.server.tio.ShowcaseServerAioHandler;
import com.freeter.server.tio.ShowcaseServerAioListener;
import com.freeter.server.voovan.VoovanServerAioHandler;

import cn.hutool.setting.dialect.Props;

/**
 * SocketConfig
 *
 * @author
 * @version 1.0
 * @since 2018/1/19
 */
@Configuration
public class SocketConfig {

	private static final Logger logger = LoggerFactory.getLogger(SocketConfig.class);

	@Bean
	public TioServer socketIOServer() {
		/*
		 * 创建Socket，并设置监听端口
		 */
		ServerAioHandler aioHandler = new ShowcaseServerAioHandler();
		ServerAioListener aioListener = new ShowcaseServerAioListener();
		ServerGroupContext serverGroupContext = new ServerGroupContext(aioHandler, aioListener);
		TioServer tioServer = new TioServer(serverGroupContext); // 可以为空
		return tioServer;
	}

	@Bean
	public AioServerSocket socketVoovanServer() {
		/*
		 * 创建Socket，并设置监听端口
		 */
		AioServerSocket serverSocket = null;
		try {
			Props props = new Props("socket_config.properties");
			String serverIp = props.getProperty("serverIp");
			int serverPort = props.getInt("serverPort");
			int idleInterval = props.getInt("serverPort");
			int readTimeout = props.getInt("serverPort");
			serverSocket = new AioServerSocket(serverIp, serverPort, readTimeout, idleInterval);
			VoovanServerAioHandler serverAioHandler = new VoovanServerAioHandler();
			serverSocket.handler(serverAioHandler);
			serverSocket.filterChain().add(new StringFilter());
			serverSocket.messageSplitter(new LineMessageSplitter());
		} catch (IOException e) {

			e.printStackTrace();
		}

		return serverSocket;
	}

}
